package utils

import (
	"strings"

	"gitee.com/liumou_site/go-network-monitoring/types"
)

// UpdateProcessStats 更新进程统计信息
func UpdateProcessStats(processStats map[int32]*types.ProcessInfo, pid int32, processName, executable, username string, conn *types.ProcessConnection) {
	stats, exists := processStats[pid]
	if !exists {
		stats = &types.ProcessInfo{
			PID:              pid,
			ProcessName:      processName,
			Executable:       executable,
			Username:         username,
			TotalConnections: 0,
			ActiveTCP:        0,
			ActiveUDP:        0,
			ListeningPorts:   []int{},
			TotalSent:        0,
			TotalRecv:        0,
			IsAlive:          true,
			SpeedUp:          0,
			SpeedDown:        0,
		}
		processStats[pid] = stats
	}

	// 更新连接统计
	stats.TotalConnections++

	// 根据协议更新计数
	if strings.HasPrefix(conn.Protocol, "tcp") {
		stats.ActiveTCP++
	} else if strings.HasPrefix(conn.Protocol, "udp") {
		stats.ActiveUDP++
	}

	// 如果是监听状态，添加到监听端口列表
	if conn.Status == "LISTEN" {
		// 检查端口是否已存在
		portExists := false
		for _, port := range stats.ListeningPorts {
			if port == conn.LocalPort {
				portExists = true
				break
			}
		}
		if !portExists {
			stats.ListeningPorts = append(stats.ListeningPorts, conn.LocalPort)
		}
	}

	// 累加连接的流量数据
	stats.TotalSent += conn.BytesSent
	stats.TotalRecv += conn.BytesRecv

	// 更新格式化文本
	stats.TotalSentText = FormatBytes(stats.TotalSent)
	stats.TotalRecvText = FormatBytes(stats.TotalRecv)
	stats.SpeedUpText = FormatSpeed(stats.SpeedUp * 1024 * 1024 / 8)     // Mbps 转 B/s
	stats.SpeedDownText = FormatSpeed(stats.SpeedDown * 1024 * 1024 / 8) // Mbps 转 B/s
}
